package FrontController;

import java.io.IOException;
import java.sql.SQLException;

import Operaciones.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FrontController extends HttpServlet{

	OperacionesBD o = new OperacionesBD();

	public void init() throws ServletException {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException{
		String userForm = request.getParameter("usuario");
		String passwdForm = request.getParameter("passwd");
		try {
		if(o.estaBaneado(userForm, passwdForm)){
			response.sendRedirect("baneado.html");
		}
		else{
		if (logado(request)) {
			String resource = request.getParameter("res");
			RequestDispatcher d = request.getRequestDispatcher(resource);
			if(d!=null){
				d.forward(request,response);
			}
			System.out.println("LOGADO ACCEDIENDO A " + resource);
		} else {
			response.sendRedirect("error.html");
				}
		}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private boolean logado(HttpServletRequest request){
		boolean logado = false;

		HttpSession session = request.getSession(false);

		String userForm = request.getParameter("usuario");
		String passwdForm = request.getParameter("passwd");
		
		if (session == null) {
			session = request.getSession();
			if (userForm == null || passwdForm == null
					|| userForm.length() == 0 || passwdForm.length() == 0) {
				logado = false;

			} else {
				if (valido(userForm, passwdForm)) {
					logado = true;
					session.setAttribute("session.user", userForm);
					session.setAttribute("session.pass", passwdForm);
				} else {
					logado = false;
				}

			}

		} else {
			if (userForm == null || passwdForm == null) {
				logado = true;
			} else {
				if (valido(userForm, passwdForm)) {
					logado = true;
					session.setAttribute("session.user", userForm);
					session.setAttribute("session.pass", passwdForm);
				} else {
					logado = false;
				}

			}
		}
		return logado;
	}

	public boolean valido(String userForm, String passwdForm){
		boolean r = false;
		try {
			return o.existeUsuario(userForm, passwdForm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return r;

	}

}
